/**
 * @Author: lena
 * @Description:http server端操作
 * @Version: 1.0.0
 * @Date: 2021/9/11 14:58
 */

package http

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

// Server1 拦截并响应请求 : http.HandleFunc
func Server1() {
	// 1.设置要拦截的请求，并进行响应
	http.HandleFunc("/hello/world", func(writer http.ResponseWriter, request *http.Request) {
		writer.Write([]byte("<h1>helloworld</h1>"))
		fmt.Println(request.URL)                  // /hello/world
		fmt.Println(request.Method)               // GET
		fmt.Println(ioutil.ReadAll(request.Body)) // [] <nil>
	})
	// 2.监听端口
	http.ListenAndServe("127.0.0.1:9000", nil)
}

/**
获取请求参数
url请求：http://127.0.0.1:9000/hello/world?a=123&b=234
页面显示：a=123,b=234
*/

func Server2() {
	// 1.拦截请求
	http.HandleFunc("/hello/world", func(writer http.ResponseWriter, request *http.Request) {
		// 1.1 获取请求参数
		query := request.URL.Query()
		a := query.Get("a")
		b := query.Get("b")
		// 1.2 将请求参数写到页面
		writer.Write([]byte("a=" + a + ",b=" + b))
	})
	// 2.监听端口
	http.ListenAndServe("127.0.0.1:9000", nil)
}

// Server3 接收post请求
func Server3() {
	// 1.拦截请求
	http.HandleFunc("/post", func(writer http.ResponseWriter, request *http.Request) {
		// 解析请求中的form数据，并将结果存放到request.PostForm/request.Form中
		request.ParseForm()
		// 获取form信息
		all, err := ioutil.ReadAll(request.Body)
		if err != nil {
			fmt.Println("[server] read fail :", err)
			return
		}
		defer request.Body.Close()
		fmt.Println("[server]", string(all)) // [server] {"name":"lena","wechat":"777"}
		// 响应
		writer.Write([]byte(`{"status":"1"}`))
	})
	// 2.监听端口
	http.ListenAndServe("127.0.0.1:9000", nil)
}
